
#include <stdbool.h>
#include <aos/aos.h>
#include <yoc/yoc.h>
#include <yoc/partition.h>

// #include "app_init.h"
#include "board.h"
#include <aos/kv.h>

#define TAG "INIT"

#ifndef CONSOLE_UART_IDX
#define CONSOLE_UART_IDX 0
#endif

extern int hal_qflash_adapt_init();

void cpu1_deassert_reset(void)
{
    *(volatile uint32_t *)0xfff21004 |= 0x01;
}

void cpu1_assert_reset(void)
{
    *(volatile uint32_t *)0xfff21004 &= ~0x01;
}

void cpu1_set_boot_addr(uint32_t boot_addr)
{
    *(volatile uint32_t *)0xfff26400 = boot_addr;
}

void cpu1_init(void)
{
    cpu1_deassert_reset();
    partition_t p = partition_open("805dtcm");
    partition_info_t *info = hal_flash_get_info(p);
    LOGD(TAG, "805dtcm->start_addr=0x%x", info->start_addr);
    LOGD(TAG, "805dtcm->image_size=0x%x", info->image_size);
    LOGD(TAG, "805dtcm load_addr=0x%x", info->load_addr);
    if (info->load_addr == ~0) {
        LOGE(TAG, "805dtcm load addr error!");
        return;
    }
    memcpy((void *)info->load_addr, (void *)(info->start_addr + info->base_addr), info->image_size);
    partition_close(p);

    p = partition_open("805ddr");
    info = hal_flash_get_info(p);
    LOGD(TAG, "805ddr->start_addr=0x%x", info->start_addr);
    LOGD(TAG, "805ddr->image_size=0x%x", info->image_size);
    LOGD(TAG, "805ddr load_addr=0x%x", info->load_addr);

    if (info->load_addr == ~0) {
        LOGE(TAG, "805ddr load addr error!");
        return;
    }
    memcpy((void *)info->load_addr, (void *)(info->start_addr + info->base_addr), info->image_size);
    partition_close(p);

    csi_dcache_clean_invalid();

    cpu1_assert_reset();
    cpu1_set_boot_addr(0xffa00000);
    cpu1_deassert_reset();
    // aos_msleep(2000);
}

void board_yoc_init()
{
    board_init();
    mtd_init();
    console_init(CONSOLE_UART_IDX, 115200, 128);
    extern int comm_uart_init(void);
    comm_uart_init();
    ulog_init();
    aos_set_log_level(AOS_LL_DEBUG);

	hal_qflash_adapt_init();

    int ret = partition_init();
    if (ret <= 0) {
        LOGE(TAG, "partition init failed");
    } else {
        LOGI(TAG, "find %d partitions", ret);
    }

    cpu1_init();

    LOGI(TAG, "Build:%s,%s",__DATE__, __TIME__);
    extern void board_cli_init();
    board_cli_init();
#if FLASH_BOOT_ENABLE
    // first_time_bootup();
#endif
    aos_kv_init("kv");
    extern void gmac_init(void);
    gmac_init();

}
